import { Component, OnInit } from '@angular/core';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { ActionSheetController, IonReorderGroup } from '@ionic/angular';
import { Base64 } from '@ionic-native/base64/ngx';
import { SQLService } from '../sql.service';
import { Utils } from '.././utils';
import {Httputils} from '../httputiles';
import{File } from '@ionic-native/file/ngx';
@Component({
  selector: 'app-camera',
  templateUrl: './camera.page.html',
  styleUrls: ['./camera.page.scss'],
})
export class CameraPage implements OnInit {
  imgurl: string;
  phototype: number;
  imgdata: string;
  filename: string;
  infos: string = '';
  constructor(private camera: Camera,
    private fileTransfer: FileTransferObject,
    public actionSheetController: ActionSheetController,
    private base64: Base64,
    private sqlService: SQLService,
    private utils: Utils,
    private httputils:   Httputils ,
  ) { }

  ngOnInit() {
    this.createTable();
  }

  createTable() {
    let sql = 'create table IF NOT EXISTS file(id VARCHAR(64), xxid VARCHAR(64), path VARCHAR(64),filename VARCHAR(64),uploaded VARCHAR(64))';
    this.sqlService.executeSql(sql).then((data) => {
      console.log(data);
      this.infos = this.infos + "创建表\\n\\t";
    }).catch((err) => {
      console.log(err);
      alert("创建表失败");

    });
  }
  insertinfo(path, filename) {
    let id = this.utils.getSequence();
    let sql = "insert into file(id,xxid,path,filename,uploaded) values('" + id + "', '12', '" + path + "','" + filename + "','否')";
    this.sqlService.executeSql(sql).then((data) => {
      console.log(data);
      this.infos = this.infos + "新照片信息\\n\\t";
    }).catch((err) => {
      console.log(err)
      this.infos = this.infos + "添加失败\\n\\t";
    });
  }
  selectunloade() {
    this.infos = this.infos + "查询\\n\\t";
    var temp = this;
    let sql = "select * from  file where  uploaded ='否' ";
    this.sqlService.executeSql(sql).then((data) => {
      // var jsobj = JSON.parse(data.res.rows);
      var datarows = data.res.rows;
      if (datarows.length !== 0) {

        let form = new FormData();
        // temp.infos =   temp.infos  + datarows.length+"/n/t"; 
        form.append('FJLB','fujianleibie');
        form.append('FJMC','fujianmingcheng');
        form.append('p_guid','pguida-a-a-as-s');

        for (let i = 0; i < datarows.length; i++) {



          var row = datarows.item(i);
          var id = row.id;
          var imgurl = row.path;
          var filename = row.filename;

          temp.infos = temp.infos + "-=-=-----" + filename + "-=-=----";
          temp.upload(id, imgurl, filename);
          // this.base64.encodeFile(imgurl).then((base64File: string) => {
          //   // const imgBlob = new Blob([reader.result], { type: file.type });
          //   form.set('file_' + filename , base64File, filename);
          // }, (err) => {
          //   console.log(err);
          // });
          // this.readFileBuffer(form,imgurl);
        }

        this.uploadfiles(form);



      } else {
        this.infos = this.infos + "----没有需要上传的图片----";
      }
      // alert("查询成功");
    }).catch((err) => {
      console.log(err)
      // alert("查询失败"+err.err.message);
      this.infos = this.infos + "----查询失败----";
    });
  }
// private readFileBuffer(form :FormData ,fileFullName:string):Promise<any>{
//   var filereader = new File();
//   return filereader.resolveLocalFilesystemUrl(fileFullName).then(
//     entry=>{

//       (entry as FileEntry).file(file => {
//       var reader = new FileReader();
//       reader.onloadend = function (e) {
//           var the_file;
//               the_file = new Blob(this.result, { type: "image/jpeg" });
//               form.append("files", the_file, 'img.jpeg');
//       };
//       reader.readAsArrayBuffer(file);
//     }
//   })
// }
  updatefileinfo(id) {
    let sql = "update file set uploaded = '是' where  id ='" + id + "' ";
    this.sqlService.executeSql(sql).then((data) => {
      // alert("更新成功" + data);
    }).catch((err) => {
      console.log(err)
      // alert("gengxin 失败");
    });
  }




  showactionsheet() {
    this.presentActionSheet();
  }
  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: 'Albums',
      buttons: [{
        text: '拍照',
        role: 'selected',
        icon: 'trash',
        handler: () => {
          this.phototype = this.camera.PictureSourceType.CAMERA;
          this.opencamera();
        }
      }, {
        text: '文件选择',
        icon: 'share',
        role: 'selected',
        handler: () => {
          this.phototype = this.camera.PictureSourceType.PHOTOLIBRARY;
          this.opencamera();
        }
      }]
    });
    await actionSheet.present();
  }

  opencamera() {
    this.filename = new Date().getTime() + '.jpg';
    const options: CameraOptions = {
      quality: 100,
      sourceType: this.phototype,
      destinationType: this.camera.DestinationType.FILE_URI,//返回值类型文件地址
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: false ,
      targetHeight: 600,
      targetWidth: 480,
    }
    this.camera.getPicture(options).then((imageData) => {
      this.imgurl = imageData;
      this.base64.encodeFile(imageData).then((base64File: string) => {
        this.imgdata = base64File;
        this.insertinfo(imageData, this.filename);
      }, (err) => {
        console.log(err);
      });
      // this.imgdata = imageData ;

    }, (err) => {
      // Handle error
    });
  }



  upload(id, imgurl, filename) {
    this.infos = this.infos + "upload......";
    const apiPath = "http://192.168.216.1:8088/jngh_app/bigfile.do"
    let options: FileUploadOptions = {
      // fileKey: 'picPath1', //默认file  
      fileName: filename, //文件名称
      headers: {},
      httpMethod: 'POST',
      // 如果要传参数，写这里
      params: {
        FJLB: "fujianleibie",
        file: imgurl,
      }
    };
    if (imgurl !== null && imgurl !== undefined) {
      this.fileTransfer.upload(imgurl, apiPath, options)
        .then((data) => {
          console.log(data);
          var jsobj = JSON.parse(data.response);
          //更新本地数据
          this.updatefileinfo(id);
          // alert("上传成功" + jsobj.files[0].name);
          this.infos = this.infos + "upload。。。。。.success";
        }, (err) => {
          console.log(err);
          // alert("上传失败" + err.message);
        });
    } else {
      this.infos = this.infos + "文件返回失败\\n\\t";
    }
  }
  uploadfiles(form){
    this.httputils.testdileupload(form).subscribe(data => {
      this.infos = this.infos + "文件返回成功\\n\\t";
    }, error =>{
      this.infos = this.infos + "文件返回失败\\n\\t";
    }
    );
  }
  download() {

  }
}
